package com.tigercel.xiangchengyun.ui.activities

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.tigercel.xiangchengyun.R
import com.tigercel.xiangchengyun.adapter.GridImageAdapter
import com.tigercel.xiangchengyun.adapter.ReportGridImgsAdapter
import com.tigercel.xiangchengyun.ui.BaseActivity
import com.tigercel.xiangchengyun.utils.FullyGridLayoutManager
import com.tigercel.xiangchengyun.utils.Global
import com.tigercel.xiangchengyun.utils.JsonUtil
import com.tigercel.xiangchengyun.utils.PreferencesUtil
import kotlinx.android.synthetic.main.activity_report_news.*
import kotlinx.android.synthetic.main.include_titlebar.*
import me.leefeng.promptlibrary.PromptDialog
import org.jetbrains.anko.toast
import java.io.File


class ReportNewsActivity : BaseActivity() {
    private lateinit var imgsAdapter: ReportGridImgsAdapter
    private var imgUris: MutableList<Uri> = ArrayList()
    private var clickTimes = 0
    private var type = ""
    private var pub_type = ""
    private var popupWindow: PopupWindow? = null
    private var gridImageAdapter: GridImageAdapter? = null
    private var manger: FullyGridLayoutManager? = null
    private var selectList: List<LocalMedia> = ArrayList()
    private var fileList: MutableList<File> = ArrayList()
    private var localDatas: PreferencesUtil? = null
    override val mContentLayoutResouredId: Int
        get() = R.layout.activity_report_news

    override fun initViews() {
        titlebar_tv.text = "发报料"
        titlebar_iv_left.setImageDrawable(resources.getDrawable(R.drawable.btn_nav_back))
        titlebar_iv_left.visibility = View.VISIBLE
        titlebar_iv_left.setOnClickListener(View.OnClickListener { this.finish() })
        titlebar_tv_right.visibility = View.VISIBLE
        titlebar_tv_right.text = "发表"
        localDatas = PreferencesUtil(this)
        titlebar_tv_right.setOnClickListener(View.OnClickListener {
            if (tv_bl_type.text == "") {
                toast("报料类型未选")
            } else {
                type = when (tv_bl_type.text) {
                    "民生" -> "1"
                    "其他" -> "2"
                    else -> "3"
                }
                pub_type = when (tv_pub_type1.text) {
                    "公开" -> "0"
                    else -> "1"
                }

                postDatas(type, pub_type)
            }

        })
//        imgsAdapter = ReportGridImgsAdapter(this, imgUris as java.util.ArrayList<Uri>?, gv_pic)
//        gv_pic.adapter = imgsAdapter
//        iv_image.setOnClickListener({
//
//        })
        manger = FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
        recycler.layoutManager = manger
        gridImageAdapter = GridImageAdapter(this, onAddPicClickListener)
        gridImageAdapter!!.setList(selectList)
        gridImageAdapter!!.setSelectMax(9)
        recycler.adapter = gridImageAdapter
        gridImageAdapter!!.setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, v: View) {
                if (selectList.size > 0) {
                    val media = selectList[position]
                    val pictureType = media.pictureType
                    val mediaType = PictureMimeType.pictureToVideo(pictureType)
                    when (mediaType) {
                        1 ->
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).themeStyle(themeId).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(this@ReportNewsActivity).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList)
                        2 ->
                            // 预览视频
                            PictureSelector.create(this@ReportNewsActivity).externalPictureVideo(media.path)
                        3 ->
                            // 预览音频
                            PictureSelector.create(this@ReportNewsActivity).externalPictureAudio(media.path)
                    }
                }
            }
        })
//        gv_pic.setOnItemClickListener { _, _, position, _ ->
//            if (position == imgsAdapter.count - 1) {
//                ImageUtils.showImagePickDialog(this)
//            }
//        }
        img_down.setOnClickListener(View.OnClickListener {
            if (clickTimes == 0) {
                img_down.setImageResource(R.drawable.btn_report_arrow_up)
                initPopupwindow()
                clickTimes++
            } else {
                img_down.setImageResource(R.drawable.btn_report_drop_down)
                clickTimes = 0
                if (popupWindow!!.isShowing) {
                    popupWindow!!.dismiss()
                } else {
                    img_down.setImageResource(R.drawable.btn_report_drop_down)
                }

            }
        })
        tv_bl_type.setOnClickListener(View.OnClickListener {
            if (clickTimes == 0) {
                img_down.setImageResource(R.drawable.btn_report_arrow_up)
                initPopupwindow()
                clickTimes++
            } else {
                img_down.setImageResource(R.drawable.btn_report_drop_down)
                clickTimes = 0
                if (popupWindow!!.isShowing) {
                    popupWindow!!.dismiss()
                }

            }
        })
        tv_pub_type1.setOnClickListener(View.OnClickListener {
            showBottomDialog()
        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        if (requestCode == ImageUtils.REQUEST_CODE_FROM_ALBUM) {
//            if (resultCode == RESULT_CANCELED) {
//                return
//            }
//            val imageUri: Uri? = data!!.data
//            if (imageUri != null) {
//                imgUris.add(imageUri)
//            }
//            updateImgs()
//
//        } else if (requestCode == ImageUtils.REQUEST_CODE_FROM_CAMERA) {
//            if (resultCode == RESULT_CANCELED) {
//                ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera)
//            } else {
//                val imageUriCamera: Uri? = ImageUtils.imageUriFromCamera
//                if (imageUriCamera != null) {
//                    imgUris.add(imageUriCamera)
//                }
//                updateImgs()
//            }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    fileList.clear()
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data)
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    for (media in selectList) {
                        Log.i("图片-----》", media.path)
                        var file = File(media.path)
                        fileList.add(file)
                    }
//                    Log.e("图片数量", fileList.size.toString())
                    gridImageAdapter!!.setList(selectList)
                    gridImageAdapter!!.notifyDataSetChanged()
                }
            }
        }
//        when (requestCode) {
//            ImageUtils.REQUEST_CODE_FROM_ALBUM ->
//                val uri:Uri? = data.data
//                if(resultCode == RESULT_CANCELED) return
//                val imgUris:if (data != null) Uri? = data.data
//
//			imgUris.add(imageUri)
//			updateImgs()
//            ImageUtils.REQUEST_CODE_FROM_CAMERA ->
//			if(resultCode == RESULT_CANCELED) {
//				ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera)
//			} else {
//				Uri imageUriCamera = ImageUtils.imageUriFromCamera
//
//				imgUris.add(imageUriCamera)
//				updateImgs()
//			}
//		}
    }

    /**
     * 更新图片显示
     */
    private fun updateImgs() {
//        if (imgUris.size > 0) {
//            iv_image.visibility = View.GONE
//            gv_pic.visibility = View.VISIBLE
//            imgsAdapter.notifyDataSetChanged()
//        } else {
//            gv_pic.visibility = View.GONE
//            iv_image.visibility = View.VISIBLE
//        }
    }

    private fun initPopupwindow() {
        val contentView = LayoutInflater.from(this).inflate(R.layout.item_mstypes, null)
        val view1 = contentView.findViewById<TextView>(R.id.tv_ms)
        val view2 = contentView.findViewById<TextView>(R.id.tv_qt)
        val view3 = contentView.findViewById<TextView>(R.id.tv_fm)
        view1.setOnClickListener(View.OnClickListener {
            tv_bl_type.text = view1.text
            if (popupWindow!!.isShowing) {
                popupWindow!!.dismiss()
                img_down.setImageResource(R.drawable.btn_report_drop_down)
                popupWindow!!.isFocusable = false
            }
        })
        view2.setOnClickListener(View.OnClickListener {
            tv_bl_type.text = view2.text
            if (popupWindow!!.isShowing) {
                popupWindow!!.dismiss()
                img_down.setImageResource(R.drawable.btn_report_drop_down)
                popupWindow!!.isFocusable = false
            }
        })
        view3.setOnClickListener(View.OnClickListener {
            tv_bl_type.text = view3.text
            if (popupWindow!!.isShowing) {
                popupWindow!!.dismiss()
                img_down.setImageResource(R.drawable.btn_report_drop_down)
                popupWindow!!.isFocusable = false
            }
        })
        popupWindow = PopupWindow(contentView, li_popup.width, 330, true)
        popupWindow!!.isOutsideTouchable = false
        popupWindow!!.isFocusable = false
        popupWindow!!.showAsDropDown(li_popup, 0, 0)

    }

    private fun showBottomDialog() {

        val bottomDialog = Dialog(this, R.style.BottomDialog)
        val contentView = LayoutInflater.from(this).inflate(R.layout.bottom_dialog_view, null)
        val tv1 = contentView.findViewById<TextView>(R.id.tv_public)
        val tv2 = contentView.findViewById<TextView>(R.id.tv_secret)
        val iv1 = contentView.findViewById<ImageView>(R.id.img_unselect)
        val iv2 = contentView.findViewById<ImageView>(R.id.img_select)
        if (tv_pub_type1.text == "公开") {
            iv1.setImageResource(R.drawable.btn_report_selected)
            iv2.setImageResource(R.drawable.btn_report_default2)
        } else {
            iv1.setImageResource(R.drawable.btn_report_default2)
            iv2.setImageResource(R.drawable.btn_report_selected)
        }
        bottomDialog.setContentView(contentView)
        val params = contentView.getLayoutParams() as ViewGroup.MarginLayoutParams
        params.width = resources.displayMetrics.widthPixels
//        params.bottomMargin = DensityUtil.dp2px(8f)
        contentView.setLayoutParams(params)
        bottomDialog.window!!.setGravity(Gravity.BOTTOM)
        bottomDialog.window!!.setWindowAnimations(R.style.BottomDialog_Animation)
        bottomDialog.setCanceledOnTouchOutside(true)
        bottomDialog.show()
        tv1.setOnClickListener(View.OnClickListener {
            tv1.setCompoundDrawables(ContextCompat.getDrawable(this, R.drawable.btn_report_selected), null, null, null)
            tv2.setCompoundDrawables(ContextCompat.getDrawable(this, R.drawable.btn_report_default2), null, null, null)
            bottomDialog.dismiss()
            tv_pub_type1.background = ContextCompat.getDrawable(this, R.drawable.radious_shape_bg_orange)
            tv_pub_type1.text = "公开"
            img_pub_type.setImageResource(R.drawable.ico_open)
        })
        tv2.setOnClickListener(View.OnClickListener {
            tv1.setCompoundDrawables(ContextCompat.getDrawable(this, R.drawable.btn_report_default2), null, null, null)
            tv2.setCompoundDrawables(ContextCompat.getDrawable(this, R.drawable.btn_report_selected), null, null, null)
            bottomDialog.dismiss()
            tv_pub_type1.background = ContextCompat.getDrawable(this, R.drawable.radious_shape_bg_orange)
            tv_pub_type1.text = "匿名"
            img_pub_type.setImageResource(R.drawable.ico_report_anonymous)
        })
    }

    private val onAddPicClickListener = object : GridImageAdapter.onAddPicClickListener {
        override fun onAddPicClick() {
            PictureSelector.create(this@ReportNewsActivity)
                    .openGallery(PictureMimeType.ofAll())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                    .theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                    .maxSelectNum(9)// 最大图片选择数量 int
//                    .minSelectNum()// 最小选择数量 int
                    .imageSpanCount(3)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .previewVideo(true)// 是否可预览视频 true or false
                    .enablePreviewAudio(true) // 是否可播放音频 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
//                    .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                    .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                    .isGif(true)// 是否显示gif图片 true or false
//                    .compressSavePath(getPath())//压缩图片保存地址
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                    .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                    .openClickSound(false)// 是否开启点击声音 true or false
                    .selectionMedia(selectList)// 是否传入已选图片 List<LocalMedia> list
                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                    .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                    .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
//                    .rotateEnabled() // 裁剪是否可旋转图片 true or false
//                    .scaleEnabled()// 裁剪是否可放大缩小图片 true or false
                    //.videoQuality(0)// 视频录制质量 0 or 1 int
                    .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                    .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                    .recordVideoSecond(60)//视频秒数录制 默认60s int
                    .isDragFrame(false)// 是否可拖动裁剪框(固定)
                    .forResult(PictureConfig.CHOOSE_REQUEST)
        }
    }

    private fun postDatas(type: String, pub_type: String) {
        var progressDailog = PromptDialog(this)
        progressDailog.showLoading("发布中,请稍后...")
        OkGo.post<String>(Global.baseUrl + Global.facilitate_upload)
                .params("user_id", localDatas!!.preferences["user_id"])
                .params("title", et_name.text.toString())
                .params("type", type)
                .params("pub_type", pub_type)
                .params("pub_loc", tv_position1.text.toString())
                .params("content", edit_feedback_content.text.toString())
                .addFileParams("img[]", fileList)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val result = response!!.body()
                        val status = JsonUtil.get_key_string("status", result)
                        val msg = JsonUtil.get_key_string("msg", result)
                        val code = JsonUtil.get_key_string("code", result)
                        val data = JsonUtil.get_key_string("data", result)
                        if (status == "0") {
                            progressDailog.showSuccess("发布成功")
                            this@ReportNewsActivity.finish()
                        } else {
                            progressDailog.showError("发布失败")
                        }
                    }

                })
    }
}
